package xiaojian.toolkit.netty.handler.callback;

import com.google.common.cache.Cache;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import org.apache.commons.collections4.Closure;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import xiaojian.toolkit.util.Identifyable;

import java.util.UUID;

public class UUIDCallbackResponseHandler<I extends Identifyable> extends ChannelInboundHandlerAdapter {
    private static Logger logger = LoggerFactory.getLogger(UUIDCallbackResponseHandler.class);

    private Cache<UUID, Closure> uuidCache;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        logger.debug("hey,channelActive");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        logger.debug("channelInactive");
    }

    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        logger.warn("", cause);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        logger.debug("message received : {}", msg);
        UUID uuid = ((I) msg).getIdentification();
        Closure closure = uuidCache.getIfPresent(uuid);
        if (closure != null) {
            closure.execute((I) msg);
            uuidCache.invalidate(uuid);
        } else {
            logger.warn("can't find matched uuid {}", uuid);
        }
    }

    public void setUuidCache(Cache<UUID, Closure> uuidCache) {
        this.uuidCache = uuidCache;
    }
}
